package com.suyeer.fastwechat.util;

import com.suyeer.basic.util.LogUtil;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.InputStream;
import java.net.URL;

/**
 * @author jun 2019/1/17.
 */
public class FwMediaUtil {
    public static String getMediaUrl(String mediaId) {
        return String.format(FwConstUtil.WX_URL_GET_MEDIA_FILE, FwUtil.getAccessToken(), mediaId);
    }

    public static String getSpeexMediaUrl(String mediaId) {
        return String.format(FwConstUtil.WX_URL_GET_SPEEX_MEDIA_FILE, FwUtil.getAccessToken(), mediaId);
    }

    public static InputStream getMediaInputStream(String mediaId) {
        return getInputStream(getMediaUrl(mediaId));
    }

    public static InputStream getSpeexMediaInputStream(String mediaId) {
        return getInputStream(getSpeexMediaUrl(mediaId));
    }

    public static void saveMediaFile(String mediaId, String localFilePath) {
        try {
            File file = new File(localFilePath);
            FileUtils.copyToFile(getMediaInputStream(mediaId), file);
        } catch (Exception e) {
            LogUtil.error(e);
        }
    }

    public static void saveSpeexMediaFile(String mediaId, String localFilePath) {
        try {
            File file = new File(localFilePath);
            FileUtils.copyToFile(getSpeexMediaInputStream(mediaId), file);
        } catch (Exception e) {
            LogUtil.error(e);
        }
    }

    private static InputStream getInputStream(String wxUrl) {
        try {
            URL url = new URL(wxUrl);
            url.openConnection().setConnectTimeout(30000);
            url.openConnection().setReadTimeout(30000);
            return url.openStream();
        } catch (Exception e) {
            LogUtil.error(e);
            return null;
        }
    }

}
